import json
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from core.security import x_user_name


from app.audit.models.audit_event import AuditEvent
from common.notice_tools import NoticeTools
from common.utils import CommonTimeUtils
from setting import config



class AuditEventHandler():
    """  AuditEvent Handler
    """
    def __init__(self):
        self.qywx_group_id = config.AUDIT_QYWX_GROUP_ID
        self.notice_tools = NoticeTools()
        


    def get_audit_event_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        事件记录表, 根据表字段-模糊查询, 获取事件记录
        """
        try:
            field_info = {field: value}
            order_info = {"create_time": "desc"}
            result = AuditEvent.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.error(f"get audit event search, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get audit event search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_audit_event_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        try:
            result = AuditEvent.filter_by_field_match(db, page, per_page,{field: value})
            if not result:
                logger.warning(f"get audit event match failed, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get audit event match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def delete_audit_event(self, db: Session, data: dict):
        """
        删除事件记录
        """
        try:
            audit_event_object = AuditEvent.get_object_by_uuid(db, data['uuid'])
            if not audit_event_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete audit event failed, uuid:{data['uuid']} not exist")
                return False

            # 删除事件记录
            AuditEvent.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete audit event error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def event_notice(self, data: dict):
        if not data["is_notice"]:
            # 不需要通知，正常返回
            logger.info(f"event_name:{data['event_name']} not to notice")
            return True
        
        msg = '## 【事件审计】 From devops' + '\n' \
              + '> 事件uuid: ' + str(data["uuid"]) + '\n' \
              + '> 用户名称：' + data["user_name"] + '\n' \
              + '> 事件名称：' + data["event_name"] + '\n' \
              + '> 事件类型：' + data["event_type"] + '\n' \
              + '> 创建时间：' + data["create_time"] + '\n' \
              + '> 事件说明：' + data["comment"][:300] + '\n' 
              
        # 发送到大群
        result = self.notice_tools.send_wechatbot(self.qywx_group_id, msg)
        if not result:
            logger.error(f"event send to wechat bot failed")
            return False

        logger.info(f"event send to wechat bot success")
        return True



    def add_audit_event(self, db: Session, data: dict):
        """
        增加事件记录
        """
        try:
            # 添加到数据库
            data["comment"] = data["comment"][:1023]
            data["user_name"] = x_user_name.get()
            result = AuditEvent.add(db, data)
            if not result:
                logger.error(f"add audit event to database failed")
                return False
            
            # 发送审计事件到企业微信群
            data["uuid"] = result.uuid
            data["create_time"] = CommonTimeUtils.strftime(result.create_time)
            result = self.event_notice(data)
            if not result:
                logger.error(f"event notice failed")
                return False
        except Exception as e:
            message = f"add audit event error"
            logger.exception(f"{message} data:{data} => {e}")
            return False

        return True



def main():
    from common.database import SessionLocal
    db = SessionLocal()
    data = {
        "xxx":"xxxx"
    }
    audit_event_handler = AuditEventHandler()
    event_data = {
        "user_name": "admin",
        "event_name": "add_alarm_rule",
        "event_type": "",
        "is_notice": 1,
        "comment": '{"uuid": 25072, "state": true, "target": "k8spod", "alarm_metrics_uuid": 108, "alarm_metrics_parm": {"namespace=": "prod"}, "operator": ">", "value": ... (762 characters truncated) ... 28\\u7387\\u8fc7\\u9ad8"}, "comment": "\\u751f\\u4ea7\\u4e1a\\u52a1\\u670d\\u52a1cpu\\u76d1\\u63a7\\u56de\\u8c03\\uff0c\\u52a8\\u6001\\u6269\\u5bb9"}'
    }
    audit_event_handler.add_audit_event(db, event_data)
    
    db.close()
    
if __name__ == "__main__":
    main()
